package library.base.mvp.presenter;

import java.util.LinkedHashMap;
import java.util.Map;

import library.base.mvp.IContract;

/**
 * @author Created by qiang.hou on 2018/3/2.
 * @version 1.0
 */
public class PresenterManager implements IContract.IPresenterManager {

    /**
     * cache：packageName + className（V） ： Presenter
     */
    private LinkedHashMap<String, BasePresenter> presenterCache = new LinkedHashMap<>();

    /**
     * private method
     */
    private PresenterManager() {
    }

    private static class InstanceHolder {
        /**
         * single instance
         */
        private static PresenterManager INSTANCE = new PresenterManager();
    }

    /**
     * get single instance
     *
     * @return instance
     */
    public static PresenterManager getInstance() {
        return InstanceHolder.INSTANCE;
    }

    /**
     * @param localClassPath packageName + className
     * @return BasePresenter
     */
    public BasePresenter getPresenter(String localClassPath) {
        /*
         * clear Invalid presenter
         */
        for (Map.Entry<String, BasePresenter> entry : presenterCache.entrySet()) {
            if (null == entry.getKey() || null == entry.getValue()) {
                presenterCache.remove(entry.getKey());
                continue;
            }
            if (!entry.getValue().isEffective() && !entry.getKey().equals(localClassPath)) {
                presenterCache.remove(entry.getKey());
            }
        }

        if (presenterCache.containsKey(localClassPath)) {
            return presenterCache.get(localClassPath);
        } else {
            return null;
        }
    }

    /**
     * @param localClassPath packageName + className
     * @param presenter      BasePresenter
     */
    public void addPresenter(String localClassPath, BasePresenter presenter) {
        if (null == localClassPath || null == presenter) {
            return;
        }
        presenterCache.put(localClassPath, presenter);
    }
}
